package com.ruicar.afs.cloud.channel.witness.controller;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruicar.afs.cloud.admin.api.dto.UserSimpleInfoDto;
import com.ruicar.afs.cloud.admin.api.feign.AfsRoleFeign;
import com.ruicar.afs.cloud.apply.admin.api.feign.ChannelOnlineSyncService;
import com.ruicar.afs.cloud.channel.affiliation.service.ChannelBaseInfoTempService;
import com.ruicar.afs.cloud.channel.blacklist.entity.BlacklistTemp;
import com.ruicar.afs.cloud.channel.blacklist.service.BlacklistTempService;
import com.ruicar.afs.cloud.channel.blacklist.utils.BlackDic;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskAssign;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskCreated;
import com.ruicar.afs.cloud.channel.channelworkflow.entity.WorkTaskDetail;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskAssignService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskCreatedService;
import com.ruicar.afs.cloud.channel.channelworkflow.service.WorkTaskDetailService;
import com.ruicar.afs.cloud.channel.common.condition.BaseInfoTypeDTO;
import com.ruicar.afs.cloud.channel.common.enums.ChannelAfsFlowEnum;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseApplyService;
import com.ruicar.afs.cloud.channel.common.feign.ChannelUseCaseService;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToApply;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToCase;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToApplyImpl;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToCaseImpl;
import com.ruicar.afs.cloud.channel.common.service.WorkProcessScheduleInfoService;
import com.ruicar.afs.cloud.channel.common.until.ChannelConfig;
import com.ruicar.afs.cloud.channel.common.until.ChannelRoleEnum;
import com.ruicar.afs.cloud.channel.common.until.RoleTypeDic;
import com.ruicar.afs.cloud.channel.filetemp.entity.ComAttachementFileTemp;
import com.ruicar.afs.cloud.channel.filetemp.service.ComAttachementFileTempService;
import com.ruicar.afs.cloud.channel.online.entity.ChannelBaseInfoTemp;
import com.ruicar.afs.cloud.channel.online.feign.ApplyFeignService;
import com.ruicar.afs.cloud.channel.register.condition.SubmitDTO;
import com.ruicar.afs.cloud.channel.register.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.channel.register.entity.ChannelListingCarTemp;
import com.ruicar.afs.cloud.channel.register.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.channel.register.utils.RegisterDic;
import com.ruicar.afs.cloud.channel.register.vo.ChannelListingCarTempVo;
import com.ruicar.afs.cloud.channel.template.service.ChannelSmsTemplateService;
import com.ruicar.afs.cloud.channel.witness.condition.ChannelWitnessInfoTempCondition;
import com.ruicar.afs.cloud.channel.witness.entity.ChannelWitnessInfoTemp;
import com.ruicar.afs.cloud.channel.witness.service.ChannelWitnessInfoTempService;
import com.ruicar.afs.cloud.channel.witness.utils.WitnessDic;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.dto.ChannelCardDTO;
import com.ruicar.afs.cloud.common.modules.apply.dto.WitnessInfoDTO;
import com.ruicar.afs.cloud.common.modules.apply.enums.CarTypeEnum;
import com.ruicar.afs.cloud.common.modules.apply.enums.ChannelNode;
import com.ruicar.afs.cloud.common.modules.apply.enums.LockFlagEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.affiliation.AffiliationRelInfo;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.vo.ComAttachmentFileDataVo;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.WorkFlowResponse;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.QueryFLowCmdRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.TaskSubmitRequest;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.response.FlowCmdBean;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.*;

import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.BUSINESS_TYPE_NEW_CAR;
import static com.ruicar.afs.cloud.channel.online.untils.ChannelOnlineConstants.BUSINESS_TYPE_OLD_CAR;

/**
 * @Method $method$
 * @Author Ice
 * @Return $return$
 * @Exception $exception$
 * @Date $date$ $time$
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/witness")
@Api(value = "ChannelWitnessInfoTemp", description = "见证人板块")
public class ChannelWitnessInfoTempController {
    private static final Logger logger = LoggerFactory.getLogger(ChannelWitnessInfoTempController.class);

    private ChannelConfig channelConfig;
    private ChannelWitnessInfoTempService channelWitnessInfoTempService;
    private ChannelBaseInfoService channelBaseInfoService;
    private BlacklistTempService blacklistTempService;
    private ChannelUseCaseService channelUseCaseService;
    private ApplyFeignService applyFeignService;
    private ChannelOnlineSyncService channelOnlineSyncService;
    private ChannelBaseInfoTempService channelBaseInfoTempService;

    private final WorkProcessScheduleInfoService workProcessScheduleInfoService;
    private final ChannelUseApplyService channelUseApplyService;

    private final WorkTaskDetailService workTaskDetailService;

    private final UidGenerator uidGenerator;
    private final WorkflowService workflowService;
    private final WorkTaskAssignService workTaskAssignService;
    private final WorkTaskCreatedService workTaskCreatedService;
    private final AfsRoleFeign afsRoleFeign;
    private final ChannelSmsTemplateService channelSmsTemplateService;

    private final SenderChannelToCaseImpl senderChannelToCaseImpl;
    private final SenderChannelToCase senderChannelToCase;
    private final ComAttachmentFileService comAttachmentFileService;
    private final ComAttachementFileTempService comAttachementFileTempService;
    private final SenderChannelToApplyImpl senderChannelToApplyImpl;
    private final SenderChannelToApply senderChannelToApply;







    @PostMapping("/getWitnessList")
    @ApiOperation(value = "分页查询见证人数据列表")
    public IResponse<IPage<ChannelWitnessInfoTemp>> getChannelListingCarTemp(@ModelAttribute  ChannelWitnessInfoTempCondition wirness) {
        //  businessType：01是新车  02 二手车  03是非直营新车二手车都有
        // ownBusinessType ：01是新车  02 二手车  03  是直营新车二手车都有

        // 第一步我要知道登录者的角色属性  是属于直营还是非直营
        List<String> role =SecurityUtils.getRoles();
        BaseInfoTypeDTO dto =new BaseInfoTypeDTO();
        // 先判断类型
        if(role.contains(ChannelRoleEnum.ROLE_ADMIN.name())){
            // 说明进来的是管理员
            dto.setBusinessType(RoleTypeDic.ALL_CAR);
            dto.setOwnBusinessType(RoleTypeDic.ALL_CAR);

        }else {
            if(role.contains(ChannelRoleEnum.ROLE_OTHER_NEW_MANAGE_WITNESS.name())||role.contains(ChannelRoleEnum.ROLE_OTHER_NEW_SEE_WITNESS.name())){
                // 进入这个说明有非直营的新车角色
                dto.setBusinessType(RoleTypeDic.NEW_CAR);
            }
            if(role.contains(ChannelRoleEnum.ROLE_OTHER_OLD_MANAGE_WITNESS.name())||role.contains(ChannelRoleEnum.ROLE_OTHER_OLD_SEE_WITNESS.name())){
                if(RoleTypeDic.NEW_CAR.equals(dto.getBusinessType())){
                    // 说明我之前新车 又有二手车
                    dto.setBusinessType(RoleTypeDic.ALL_CAR);
                }else {
                    // 说明我只有二手车
                    dto.setBusinessType(RoleTypeDic.OLD_CAR);
                }
            }
            // 再去看看他有直营的角色吗
            if(role.contains(ChannelRoleEnum.ROLE_OWN_NEW_MANAGE_WITNESS.name())||role.contains(ChannelRoleEnum.ROLE_OWN_NEW_SEE_WITNESS.name())){
                dto.setOwnBusinessType(RoleTypeDic.NEW_CAR);
            }
            if(role.contains(ChannelRoleEnum.ROLE_OWN_OLD_MANAGE_WITNESS.name())||role.contains(ChannelRoleEnum.ROLE_OWN_OLD_SEE_WITNESS.name())){
                if(RoleTypeDic.NEW_CAR.equals(dto.getOwnBusinessType())){
                    // 说明我之前新车 又有二手车
                    dto.setOwnBusinessType(RoleTypeDic.ALL_CAR);
                }else {
                    // 说明我只有二手车
                    dto.setOwnBusinessType(RoleTypeDic.OLD_CAR);
                }
            }
        }
        if((dto.getBusinessType()==null||dto.getBusinessType()=="")&&(dto.getOwnBusinessType()==null||dto.getOwnBusinessType()=="")){
            return IResponse.fail("暂无权限查询！");
        }
        Map<String,String> headers = new HashMap<String,String>();
        headers.put("clientId",channelConfig.getCaseClientId());
        headers.put("clientSecret",channelConfig.getCaseClientSecret());
        IResponse result=channelUseCaseService.getBaseInfoByRole(dto,headers);
        IPage<List<ChannelWitnessInfoTemp>> list=null;
        Page page = new Page(wirness.getPageNumber(), wirness.getPageSize());

        // 声明一个 合作商id 集合
        List<Long> ids =new ArrayList<>();
        if("0000".equals(result.getCode())){
            List<ChannelBaseInfoTemp> base= JSON.parseArray(JSON.toJSONString(result.getData()), ChannelBaseInfoTemp.class);
            if(base.size()>0){
                for (int i=0;i<base.size();i++){
                    ids.add(base.get(i).getId());
                }
                // 这边 是为了看自己的业务属性 去查询数据
                if(RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                    //说明我直营非直营都可以做  不要做任何考虑，开心吧   13
                    list =channelWitnessInfoTempService.getWitnessList(page,wirness,ids);
                }else if(RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&dto.getOwnBusinessType()==null){
                    //  说明非直营我全都有  并且没有直营属性  10
                    list =channelWitnessInfoTempService.getWitnessOnlyOtherAll(page,wirness,ids);
                }else if(RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&!RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                    //  说明非直营的我全都有  直营的只有单一属性
                    if(RoleTypeDic.NEW_CAR.equals(dto.getOwnBusinessType())){
                        //  说明单一属性的是新车 11
                        list =channelWitnessInfoTempService.getWitnessOtherAllOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_NEW);
                    }else {
                        // 说明单一属性的是二手车   12
                        list =channelWitnessInfoTempService.getWitnessOtherAllOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_OLD);
                    }

                }else  if(dto.getBusinessType()!=null&&!RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&dto.getOwnBusinessType()==null){
                    // 说明 只有非直营 并且属性单一
                    if(RoleTypeDic.NEW_CAR.equals(dto.getBusinessType())){
                        //  说明单一属性的是新车  1
                        list =channelWitnessInfoTempService.getWitnessOtherOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_NEW);
                    }else {
                        // 说明单一属性的是二手车   6
                        list =channelWitnessInfoTempService.getWitnessOtherOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_OLD);
                    }
                }else if(dto.getBusinessType()!=null&&!RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&dto.getOwnBusinessType()!=null&&RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){

                    //  说明我 非直营单一属性   直营属性也是单一
                    if(RoleTypeDic.NEW_CAR.equals(dto.getBusinessType())){
                        // 说明我非直营新车
                        if(RoleTypeDic.NEW_CAR.equals(dto.getOwnBusinessType())){
                            // 说明我直营是新车  3
                            list =channelWitnessInfoTempService.getWitnessOtherOnlyOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_NEW,WitnessDic.BUSINESS_ATTRIBUTES_NEW);
                        }else {
                            // 说明我直营 是二手车  4
                            list =channelWitnessInfoTempService.getWitnessOtherOnlyOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_NEW,WitnessDic.BUSINESS_ATTRIBUTES_OLD);
                        }

                    }else {
                        //  说明我非直营是二手车
                        if(RoleTypeDic.NEW_CAR.equals(dto.getOwnBusinessType())){
                            // 说明我直营是新车  7
                            list =channelWitnessInfoTempService.getWitnessOtherOnlyOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_OLD,WitnessDic.BUSINESS_ATTRIBUTES_NEW);
                        }else {
                            // 说明我直营是二手车 8
                            list =channelWitnessInfoTempService.getWitnessOtherOnlyOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_OLD,WitnessDic.BUSINESS_ATTRIBUTES_OLD);

                        }
                    }

                }else if(dto.getBusinessType()!=null&&!RoleTypeDic.ALL_CAR.equals(dto.getBusinessType())&&RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                    // 说明我非直营 单一属性  我直营全部
                    if(RoleTypeDic.NEW_CAR.equals(dto.getBusinessType())){
                        // 说明我非值新   配直营全部  5
                        list =channelWitnessInfoTempService.getWitnessOtherOnlyOwnAll(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_NEW);
                    }else {
                        // 说明我是二手车   配直营全部   9
                        list =channelWitnessInfoTempService.getWitnessOtherOnlyOwnAll(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_OLD);
                    }

                }else if(dto.getBusinessType()==null&&RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())){
                    // 说明我非值 没有   直营全有   16
                    list =channelWitnessInfoTempService.getWitnessOwnAll(page,wirness,ids);
                }else if(dto.getBusinessType()==null&&!RoleTypeDic.ALL_CAR.equals(dto.getOwnBusinessType())&&dto.getOwnBusinessType()!=null){
                    // 说明我非直  没有   直营单一属性
                    if(RoleTypeDic.NEW_CAR.equals(dto.getOwnBusinessType())){
                        // 说明我只有直营新车  14
                        list =channelWitnessInfoTempService.getWitnessOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_NEW);
                    }else {
                        // 说明我只有直营二手车 15
                        list =channelWitnessInfoTempService.getWitnessOwnOnly(page,wirness,ids,WitnessDic.BUSINESS_ATTRIBUTES_OLD);
                    }

                }
            }
        }else {
            throw new AfsBaseException("查询合作商失败！");
        }



        return IResponse.success(list);
    }

    @PostMapping("/getChannelWitnessListData")
    @ApiOperation(value = "分页查询见证人数据列表")
    public IResponse<IPage<ChannelWitnessInfoTemp>> getChannelWitnessListData(@RequestBody  ChannelWitnessInfoTempCondition wirness) {


        Page page = new Page(wirness.getPageNumber(), wirness.getPageSize());

        IPage<List<ChannelWitnessInfoTemp>> list =channelWitnessInfoTempService.getChannelWitnessListData(page,wirness);

        return IResponse.success(list);
    }

    @PostMapping("/getWitnessUseChannel")
    @ApiOperation(value = "渠道合作商分页查询见证人数据列表")
    public IResponse<IPage<ChannelWitnessInfoTemp>> getWitnessUseChannel(@RequestBody  ChannelWitnessInfoTempCondition wirness) {


        Page page = new Page(wirness.getPageNumber(), wirness.getPageSize());

        IPage<List<ChannelWitnessInfoTemp>> list =channelWitnessInfoTempService.getWitnessUseChannel(page,wirness);

        return IResponse.success(list);
    }


    @PostMapping("/getRegister")
    @ApiOperation(value = "分页获取见证人审核列表")
    public IResponse<IPage<ChannelListingCarTempVo>> getRegister(@RequestBody ChannelWitnessInfoTempCondition channel) {
        // 先获取登陆人的角色
        List<String> roles =SecurityUtils.getRoles();
        if(roles.size()<=0){
            throw new AfsBaseException("此用户暂无权限查询！");
        }
        // 先去查询 待审批的数据信息
        Page page = new Page(channel.getPageNumber(), channel.getPageSize());
        IPage<List<ChannelWitnessInfoTemp>>  list =channelWitnessInfoTempService.getRegister(page, channel,roles, AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_WITNESS));
        return IResponse.success(list);

    }

    @Transactional
    @PostMapping("/sendMessageByBlack")
    @ApiOperation(value = "见证人触发黑名单发送信息")
    public IResponse<ChannelListingCarTemp> sendMessageByBlack(@RequestBody ChannelWitnessInfoTemp channel) throws ParseException, JsonProcessingException {
        channelSmsTemplateService.sendMessageByWitness(channel);
        return IResponse.success(channel);
    }


    @Transactional
    @PostMapping("/save")
    @ApiOperation(value = "保存见证人数据")
    public IResponse<ChannelWitnessInfoTemp> save(@Valid @RequestBody ChannelWitnessInfoTemp channel) throws ParseException {
        // 第一步去调用进件接口查看这个见证人有没有在其他合作商有账号
        List<ChannelCardDTO> upIds =new ArrayList<>();
        ChannelCardDTO dto =new ChannelCardDTO();
        dto.setCard(channel.getWitnessIdCard());
        dto.setChannelId(channel.getChannelId());
        upIds.add(dto);
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
        requestHeader.put("clientSecret",channelConfig.getApplyAdminClientSecret());
        IResponse result=channelOnlineSyncService.checkWitness(upIds,requestHeader);
        if(CommonConstants.SUCCESS.equals(result.getCode())){
            if("true".equals(result.getData().toString())){
                channelSmsTemplateService.sendMessageByWitness(channel);
                throw new AfsBaseException("见证人备案信息异常！");
            }

        }else {
            throw new AfsBaseException("见证人校验异常！");
        }


        // 根据合作商id 查询合作商名称
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(channel.getChannelId());

        //创建人
        channel.setCreateBy(SecurityUtils.getUsername());
        // 第一步先看看见证人是不是在黑名单里
        if(blacklistTempService.list(Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getBlacklistType, BlackDic.BLACKLIST_TYPE_WITNESS).eq(BlacklistTemp::getIdCode,channel.getWitnessIdCard()).eq(BlacklistTemp::getWeatherBlacklist,BlackDic.WEATHER_BLACKLIST_YES).eq(BlacklistTemp::getIdType,BlackDic.ID_TYPE_ID)).size()>0){
            return IResponse.fail("添加失败！该用户在黑名单中！");
        }

        // 如果不在黑名单里，看看这个见证人在该合作商是否存在这个类型
        List<ChannelWitnessInfoTemp> witness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).eq(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                .eq(ChannelWitnessInfoTemp::getBusinessAttributes, channel.getBusinessAttributes()).notIn(ChannelWitnessInfoTemp::getStatus,WitnessDic.STATUS_REFUSE));
        if (witness.size() > 0) {
            if(WitnessDic.STATUS_PASS.equals(witness.get(0).getStatus())){
                return IResponse.fail("添加失败，该用户已启用无需重复添加！");
            }
            return IResponse.fail("添加失败，该用户已存在，请去修改!");
        } else {
            List<String> statusList =new ArrayList<>();
            statusList.add(WitnessDic.STATUS_STOP);
            statusList.add(WitnessDic.STATUS_REFUSE);
            statusList.add(WitnessDic.STATUS_ZORO_DRAFT);
            // 判断这个客户目前有没有未停用的其他合作商
            List<ChannelWitnessInfoTemp> stopWitness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).notIn(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                    .notIn(ChannelWitnessInfoTemp::getStatus,statusList));
            if (stopWitness.size() > 0) {
                // 如果有直接结束告诉前端
                return IResponse.fail("该见证人已存其他未停用的合作商！");
            } else {

                // 如果没有合作商，直接加入
                channel.setCreateBy(SecurityUtils.getUsername());
                channel.setCreateTime(new Date(System.currentTimeMillis()));
                channel.setDelFlag(WitnessDic.DEL_FLAG_USABLE);
                channel.setMsgSource(RegisterDic.sourceChannel);
                channel.setChannelBelong(baseInfoTemp.getChannelBelong());
                if(WitnessDic.STATUS_PASS.equals(channel.getStatus())){
                    channel.setApproveTime(new Date(System.currentTimeMillis()));
                }
                channelWitnessInfoTempService.save(channel);
                // 通过后要把数据推给进件和案件
                ChannelWitnessInfoTemp temp=channelWitnessInfoTempService.getById(channel.getId());
                if(WitnessDic.STATUS_PASS.equals(temp.getStatus())){
                    // 把影像资料更新一下
                    comAttachementFileTempService.remove(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,channel.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.witnessApply.toString()));
                    //把影像资料存储
                    List<ComAttachmentFile> fileList =comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,channel.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.witnessApply.toString()));
                    if(fileList.size()>0){
                        for(ComAttachmentFile file:fileList){
                            ComAttachementFileTemp fileTemp=new ComAttachementFileTemp();
                            BeanUtils.copyProperties(file, fileTemp);
                            fileTemp.setId(null);
                            comAttachementFileTempService.save(fileTemp);
                        }
                    }
                    // 推给进件和进件
                    this.sendCaseAdmin(temp);

                }

                return IResponse.success(Boolean.TRUE).setMsg("录入成功").setData(channel);
            }
        }


    }


    @Transactional
    @PostMapping("/applySave")
    @ApiOperation(value = "保存见证人数据")
    public IResponse<ChannelWitnessInfoTemp> applySave(@Valid @RequestBody ChannelWitnessInfoTemp channel) throws ParseException, JsonProcessingException {
        // 第一步去调用进件接口查看这个见证人有没有在其他合作商有账号
        List<ChannelCardDTO> upIds =new ArrayList<>();
        ChannelCardDTO dto =new ChannelCardDTO();
        dto.setCard(channel.getWitnessIdCard());
        dto.setChannelId(channel.getChannelId());
        upIds.add(dto);
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
        requestHeader.put("clientSecret",channelConfig.getApplyAdminClientSecret());
        IResponse result=channelOnlineSyncService.checkWitness(upIds,requestHeader);
        if(CommonConstants.SUCCESS.equals(result.getCode())){
            if("true".equals(result.getData().toString())){
                channelSmsTemplateService.sendMessageByWitness(channel);
                throw new AfsBaseException("见证人备案信息异常！");
            }

        }else {

            throw new AfsBaseException("见证人校验异常！");
        }

        // 根据合作商id 查询合作商名称
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(channel.getChannelId());

        //创建人
        channel.setCreateBy(SecurityUtils.getUsername());
        // 第一步先看看见证人是不是在黑名单里
        if(blacklistTempService.list(Wrappers.<BlacklistTemp>query().lambda().eq(BlacklistTemp::getBlacklistType, BlackDic.BLACKLIST_TYPE_WITNESS).eq(BlacklistTemp::getIdCode,channel.getWitnessIdCard()).eq(BlacklistTemp::getWeatherBlacklist,BlackDic.WEATHER_BLACKLIST_YES).eq(BlacklistTemp::getIdType,BlackDic.ID_TYPE_ID)).size()>0){
            return IResponse.fail("添加失败！该用户在黑名单中！");
        }

        // 如果不在黑名单里，看看这个见证人在该合作商是否存在这个类型
        List<ChannelWitnessInfoTemp> witness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).eq(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                .eq(ChannelWitnessInfoTemp::getBusinessAttributes, channel.getBusinessAttributes()).notIn(ChannelWitnessInfoTemp::getStatus,WitnessDic.STATUS_REFUSE));
        if (witness.size() > 0) {
            if(WitnessDic.STATUS_PASS.equals(witness.get(0).getStatus())){
                return IResponse.fail("添加失败，该用户已启用无需重复添加！");
            }
            return IResponse.fail("添加失败，该用户已存在，请去修改!");
        } else {
            List<String> statusList =new ArrayList<>();
            statusList.add(WitnessDic.STATUS_STOP);
            statusList.add(WitnessDic.STATUS_REFUSE);
            statusList.add(WitnessDic.STATUS_ZORO_DRAFT);
            // 判断这个客户目前有没有未停用的其他合作商
            List<ChannelWitnessInfoTemp> stopWitness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).notIn(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                    .notIn(ChannelWitnessInfoTemp::getStatus, statusList));
            if (stopWitness.size() > 0) {
                channelSmsTemplateService.sendMessageByWitness(channel);
                // 如果有直接结束告诉前端
                return IResponse.fail("该见证人信息异常！");
            } else {

                // 如果没有合作商，直接加入
                channel.setCreateBy(SecurityUtils.getUsername());
                channel.setCreateTime(new Date(System.currentTimeMillis()));
                channel.setDelFlag(WitnessDic.DEL_FLAG_USABLE);
                channel.setMsgSource(RegisterDic.sourceApply);
                channel.setChannelBelong(baseInfoTemp.getChannelBelong());
                channelWitnessInfoTempService.save(channel);
                // 如果是审核中 那么就进入工作流
                if(WitnessDic.STATUS_APPROVE.equals(channel.getStatus())){
                    this.foundWorkFlow(channel);
                }

                return IResponse.success(Boolean.TRUE).setMsg("录入成功").setData(channel);
            }
        }
    }
    // 发起一个新的工作流
    public  void foundWorkFlow(ChannelWitnessInfoTemp temp) throws JsonProcessingException {
        StartFlowRequest startFlowNew = new StartFlowRequest();
        startFlowNew.setAfsFlowKey(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_WITNESS));
        startFlowNew.setBizDataId(uidGenerator.getUID()+"");
        startFlowNew.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_WITNESS));
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(temp);
        JSONObject cancelJson = JSONObject.parseObject(json);
        // 判断业务类型
        if(WitnessDic.BUSINESS_ATTRIBUTES_NEW.equals(temp.getBusinessAttributes())){
            //业务类型:新车
            cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.BUSINESS_TYPE),BUSINESS_TYPE_NEW_CAR);
        }else if(WitnessDic.BUSINESS_ATTRIBUTES_OLD.equals(temp.getBusinessAttributes())){
            //业务类型:二手车
            cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.BUSINESS_TYPE),BUSINESS_TYPE_OLD_CAR);
        }else {
            throw new AfsBaseException("获取业务类型失败！");
        }
        // 判断渠道归属
        if(temp.getChannelBelong()==""||temp.getChannelBelong()==null){
            throw new AfsBaseException("获取渠道归属失败！");
        }else {
            cancelJson.put(AfsEnumUtil.key(ChannelAfsFlowEnum.CHANNEL_BELONG),temp.getChannelBelong());
        }
        workflowService.startWorkFlow(startFlowNew,cancelJson);


        //保存业务相关数据、用户前端逻辑判断
        WorkTaskDetail detail = new WorkTaskDetail();
        detail.setBizDataId(startFlowNew.getBizDataId());
        detail.setName(temp.getWitnessName());
        detail.setFlowName(AfsEnumUtil.desc(ChannelAfsFlowEnum.CHANNEL_WITNESS));
        // 判断业务类型
        if(WitnessDic.BUSINESS_ATTRIBUTES_NEW.equals(temp.getBusinessAttributes())){
            //业务类型:新车
            detail.setBusinessType(BUSINESS_TYPE_NEW_CAR);
        }else if(WitnessDic.BUSINESS_ATTRIBUTES_OLD.equals(temp.getBusinessAttributes())){
            //业务类型:二手车
            detail.setBusinessType(BUSINESS_TYPE_OLD_CAR);
        }else {
            throw new AfsBaseException("获取业务类型失败！");
        }

        //挂牌车id绑定
        detail.setBusinessKey(temp.getId());
        workTaskDetailService.save(detail);

        // 给挂牌车数据绑定工作流实例id
        temp.setDataId(Long.valueOf(startFlowNew.getBizDataId()));
        channelWitnessInfoTempService.updateById(temp);
    }

    //  发起工作流的方法
    public void sendWorkflow(ChannelWitnessInfoTemp temp) throws JsonProcessingException {
        //发起挂牌车审核流程
        WorkTaskDetail workTaskDetail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda()
                .eq(WorkTaskDetail::getBusinessKey, temp.getId().toString()).eq(WorkTaskDetail::getBizDataId,temp.getDataId().toString()));
        if(workTaskDetail ==null){
            this.foundWorkFlow(temp);
        }else {
            log.info("*********************返回的时候传递的流程id"+temp.getDataId().toString());
            // 如果是通过
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(temp.getId());
            dto.setApprove("1");
            dto.setBizDataId(temp.getDataId().toString());
            submit(dto);
        }

    }
    //  审核发起工作流
    public void submit(SubmitDTO dto) throws JsonProcessingException {
        log.info("c***************************这一次的流程id+"+ dto.getBizDataId());
            WorkTaskAssign assgin = workTaskAssignService.getOne(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, dto.getBizDataId().toString()));

        //提交完成之后删除其他人员代办
        List<WorkTaskAssign> assignList = workTaskAssignService.list(Wrappers.<WorkTaskAssign>query().lambda().eq(WorkTaskAssign::getBizDataId, dto.getBizDataId()));
        //删除剩余节点数据信息
           for(int i=0;i<assignList.size();i++){
               workTaskAssignService.removeById(assignList.get(i).getId().toString());
            }
        log.info("c***************************流程数据+"+assgin);
        WorkTaskCreated created = workTaskCreatedService.getOne(Wrappers.<WorkTaskCreated>query().lambda().eq(WorkTaskCreated::getBizDataId, dto.getBizDataId()));
        WorkTaskDetail detail = workTaskDetailService.getOne(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBizDataId, dto.getBizDataId()));


        TaskSubmitRequest taskSubmitRequest = new TaskSubmitRequest();
        taskSubmitRequest.setGwtUserId(assgin.getAssignId());
        taskSubmitRequest.setAfsFlowKey(created.getAfsFlowKey());
        taskSubmitRequest.setBizDataId(created.getBizDataId());
        QueryFLowCmdRequest request = new QueryFLowCmdRequest();
        request.setFlowInstanceId(created.getFlowInstanceId());
        WorkFlowResponse<List<FlowCmdBean>> cmdResponse = workflowService.queryFlowCmd(request);
        List<FlowCmdBean> cmdList = cmdResponse.getAfsData();
        FlowCmdBean cmd = workTaskCreatedService.channelApprove(dto.getApprove(),cmdList);

        ChannelWitnessInfoTemp  temp =channelWitnessInfoTempService.getById(dto.getRegisterId());
        if(cmd!=null){
            taskSubmitRequest.setCmdId(cmd.getId());
            ObjectMapper mapper = new ObjectMapper();
            //获取配置节点信息
            String json = mapper.writeValueAsString(temp);
            JSONObject cancelJson = JSONObject.parseObject(json);
            workflowService.taskSubmit(taskSubmitRequest,cancelJson);


        }else {
            throw new AfsBaseException("提交工作流失败！");
        }
    }


    @Transactional
    @PostMapping("/edit")
    @ApiOperation(value = "修改见证人数据")
    public IResponse<ChannelWitnessInfoTemp> edit(@Valid @RequestBody ChannelWitnessInfoTemp channel) throws ParseException {
        // 第一步去调用进件接口查看这个见证人有没有在其他合作商有账号
        List<ChannelCardDTO> upIds =new ArrayList<>();
        ChannelCardDTO dto =new ChannelCardDTO();
        dto.setCard(channel.getWitnessIdCard());
        dto.setChannelId(channel.getChannelId());
        upIds.add(dto);
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
        requestHeader.put("clientSecret",channelConfig.getApplyAdminClientSecret());
        IResponse result=channelOnlineSyncService.checkWitness(upIds,requestHeader);
        if(CommonConstants.SUCCESS.equals(result.getCode())){
            if("true".equals(result.getData().toString())){
                channelSmsTemplateService.sendMessageByWitness(channel);
                throw new AfsBaseException("见证人备案信息异常！");
            }
        }else {
            throw new AfsBaseException("见证人校验异常！");
        }
        // 根据合作商id 查询合作商名称
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(channel.getChannelId());
        //创建人
        channel.setUpdateBy(SecurityUtils.getUsername());
        // 如果不在黑名单里，看看这个见证人在该合作商是否存在这个类型
        List<ChannelWitnessInfoTemp> witness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).eq(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                .eq(ChannelWitnessInfoTemp::getBusinessAttributes, channel.getBusinessAttributes()).notIn(ChannelWitnessInfoTemp::getId,channel.getId()).notIn(ChannelWitnessInfoTemp::getStatus,WitnessDic.STATUS_REFUSE));
        if (witness.size() > 0) {
            if(WitnessDic.STATUS_PASS.equals(witness.get(0).getStatus())){
                return IResponse.fail("修改失败，该用户已启存启用的该类型！");
            }
            return IResponse.fail("修改失败，该用户已存在该类型");
        } else {
            List<String> statusList =new ArrayList<>();
            statusList.add(WitnessDic.STATUS_STOP);
            statusList.add(WitnessDic.STATUS_REFUSE);
            statusList.add(WitnessDic.STATUS_ZORO_DRAFT);
            // 判断这个客户目前有没有未停用的其他合作商
            List<ChannelWitnessInfoTemp> stopWitness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).notIn(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                    .notIn(ChannelWitnessInfoTemp::getStatus, statusList));
            if (stopWitness.size() > 0) {
                // 如果有直接结束告诉前端
                return IResponse.fail("该见证人已存其他未停用的合作商！");
            } else {
                // 如果没有合作商，直接加入
                channel.setUpdateBy(SecurityUtils.getUsername());
                channel.setUpdateTime(new Date(System.currentTimeMillis()));
                channel.setDelFlag(WitnessDic.DEL_FLAG_USABLE);
                channel.setChannelBelong(baseInfoTemp.getChannelBelong());
                if(WitnessDic.STATUS_PASS.equals(channel.getStatus())){
                    channel.setApproveTime(new Date(System.currentTimeMillis()));
                    this.sendCaseAdmin(channel);
                }
                channelWitnessInfoTempService.updateById(channel);
                // 通过后要把数据推给进件和案件
                ChannelWitnessInfoTemp temp=channelWitnessInfoTempService.getById(channel.getId());
                if(WitnessDic.STATUS_PASS.equals(temp.getStatus())){
                    // 把影像资料更新一下
                    comAttachementFileTempService.remove(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,channel.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.witnessApply.toString()));
                    //把影像资料存储
                    List<ComAttachmentFile> fileList =comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,channel.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.witnessApply.toString()));
                    if(fileList.size()>0){
                        for(ComAttachmentFile file:fileList){
                            ComAttachementFileTemp fileTemp=new ComAttachementFileTemp();
                            BeanUtils.copyProperties(file, fileTemp);
                            fileTemp.setId(null);
                            comAttachementFileTempService.save(fileTemp);
                        }
                        // 查询一遍临时表数据
                        List<ComAttachementFileTemp> fileTempList =comAttachementFileTempService.list(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,channel.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.witnessApply.toString()));
                        // 同步到进件
                        List<ComAttachmentFile> list2 = JSONUtil.parseArray(fileTempList).toList(ComAttachmentFile.class);
                        ComAttachmentFileDataVo dataVo=new ComAttachmentFileDataVo();
                        dataVo.setComAttachmentFileList(list2);
                        AfsTransEntity<ComAttachmentFileDataVo> transEntity = new AfsTransEntity<>();
                        transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_CHANNEL_FILE_APPLY);
                        transEntity.setData(dataVo);
                        senderChannelToApply.sendWitnessFile(transEntity);
                    }
                    // 推给进件和进件
                    this.sendCaseAdmin(temp);

                }
                return IResponse.success(Boolean.TRUE).setMsg("修改成功！").setData(channel);
            }
        }
    }

    @Transactional
    @PostMapping("/editApply")
    @ApiOperation(value = "修改见证人数据")
    public IResponse<ChannelWitnessInfoTemp> editApply(@Valid @RequestBody ChannelWitnessInfoTemp channel) throws ParseException, JsonProcessingException {
        // 第一步去调用进件接口查看这个见证人有没有在其他合作商有账号
        List<ChannelCardDTO> upIds =new ArrayList<>();
        ChannelCardDTO dto =new ChannelCardDTO();
        dto.setCard(channel.getWitnessIdCard());
        dto.setChannelId(channel.getChannelId());
        upIds.add(dto);
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
        requestHeader.put("clientSecret",channelConfig.getApplyAdminClientSecret());
        IResponse result=channelOnlineSyncService.checkWitness(upIds,requestHeader);
        if(CommonConstants.SUCCESS.equals(result.getCode())){
            if("true".equals(result.getData().toString())){
                channelSmsTemplateService.sendMessageByWitness(channel);
                throw new AfsBaseException("见证人备案信息异常！");
            }
        }else {
            throw new AfsBaseException("见证人校验异常！");
        }
        // 去更新影像数据
        comAttachmentFileService.remove(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,channel.getId().toString()).eq(ComAttachmentFile::getBelongNo, ChannelNode.witnessApply.toString()));
        // 再重新加载影像资料
        if(channel.getFileList().size()>0){
            for (ComAttachmentFile FileList :channel.getFileList()){
                ComAttachmentFile file =new ComAttachmentFile();
                BeanUtils.copyProperties(FileList, file);
                file.setId(null);
                comAttachmentFileService.save(file);
            }

        }

        // 先查询下原来的信息
        ChannelWitnessInfoTemp old =channelWitnessInfoTempService.getById(channel);
        // 根据合作商id 查询合作商名称
        ChannelBaseInfoTemp baseInfoTemp = channelBaseInfoTempService.getById(old.getChannelId());
        //创建人
        channel.setUpdateBy(SecurityUtils.getUsername());

        // 如果不在黑名单里，看看这个见证人在该合作商是否存在这个类型
        List<ChannelWitnessInfoTemp> witness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).eq(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                .eq(ChannelWitnessInfoTemp::getBusinessAttributes, channel.getBusinessAttributes()).notIn(ChannelWitnessInfoTemp::getId,channel.getId()).notIn(ChannelWitnessInfoTemp::getStatus,WitnessDic.STATUS_REFUSE));
        if (witness.size() > 0) {
            if(WitnessDic.STATUS_PASS.equals(witness.get(0).getStatus())){
                return IResponse.fail("修改失败，该用户已启存启用的该类型！");
            }
            return IResponse.fail("修改失败，该用户已存在该类型");
        } else {
            List<String> statusList =new ArrayList<>();
            statusList.add(WitnessDic.STATUS_STOP);
            statusList.add(WitnessDic.STATUS_REFUSE);
            statusList.add(WitnessDic.STATUS_ZORO_DRAFT);
            // 判断这个客户目前有没有未停用的其他合作商
            List<ChannelWitnessInfoTemp> stopWitness = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard, channel.getWitnessIdCard()).notIn(ChannelWitnessInfoTemp::getChannelId,channel.getChannelId())
                    .notIn(ChannelWitnessInfoTemp::getStatus, statusList));
            if (stopWitness.size() > 0) {
                channelSmsTemplateService.sendMessageByWitness(channel);
                // 如果有直接结束告诉前端
                return IResponse.fail("该见证人信息数据异常！");
            } else {
                // 如果没有合作商，直接加入
                channel.setUpdateBy(SecurityUtils.getUsername());
                channel.setUpdateTime(new Date(System.currentTimeMillis()));
                channel.setDelFlag(WitnessDic.DEL_FLAG_USABLE);
                channel.setMsgSource(RegisterDic.sourceApply);
                channel.setChannelBelong(baseInfoTemp.getChannelBelong());
                channelWitnessInfoTempService.updateById(channel);
                // 再查下下数据
                ChannelWitnessInfoTemp newChannel =channelWitnessInfoTempService.getById(channel);
                // 如果是审核中 那么就进入工作流
                if(WitnessDic.STATUS_APPROVE.equals(channel.getStatus())){
                    if(WitnessDic.STATUS_RETURN.equals(old.getStatus())){
                        this.sendWorkflow(newChannel);
                    }else {
                        this.foundWorkFlow(newChannel);
                    }
                }
                return IResponse.success(Boolean.TRUE).setMsg("修改成功！").setData(channel);
            }
        }

    }
    //  发送信息给案件和进件 admin
    public void sendCaseAdmin(ChannelWitnessInfoTemp temp){
        channelWitnessInfoTempService.update(Wrappers.<ChannelWitnessInfoTemp>lambdaUpdate().set(ChannelWitnessInfoTemp::getStartStopReason,null).eq(ChannelWitnessInfoTemp::getId,temp.getId()));

        ChannelWitnessInfoTemp aa =channelWitnessInfoTempService.getById(temp.getId());


        // 开账号
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
        requestHeader.put("clientSecret",channelConfig.getApplyAdminClientSecret());
        WitnessInfoDTO bb =new WitnessInfoDTO();
        bb.setApproveTime(aa.getApproveTime());
        if(WitnessDic.BUSINESS_ATTRIBUTES_NEW.equals(aa.getBusinessAttributes())){
            bb.setBusinessAttributes(CarTypeEnum.newCar);
        }else {
            bb.setBusinessAttributes(CarTypeEnum.oldCar);
        }
        bb.setCeaseTime(aa.getCeaseTime());
        bb.setChannelId(aa.getChannelId().toString());
        bb.setStartStopReason(aa.getStartStopReason());
        bb.setStatus(LockFlagEnum.YES);
        bb.setWitnessIdCard(aa.getWitnessIdCard());
        bb.setWitnessName(aa.getWitnessName());
        bb.setWitnessValidityAuthorization(aa.getWitnessValidityAuthorization());

        List<WitnessInfoDTO> cc= new ArrayList<WitnessInfoDTO>();
        cc.add(bb);
        // 测试暂时注释
        IResponse apply =channelOnlineSyncService.syncWitnessInfo(cc,requestHeader);
        if(CommonConstants.SUCCESS.equals(apply.getCode())){

        }else {
            throw new AfsBaseException("同步进件数据失败！");
        }

        // 发送给案件
        Map<String,String> headers = new HashMap<String,String>();
        headers.put("clientId",channelConfig.getCaseClientId());
        headers.put("clientSecret",channelConfig.getCaseClientSecret());
        IResponse result = channelUseCaseService.getCaseSave(aa,headers);
        if(CommonConstants.SUCCESS.equals(result.getCode())){

        }else {
            throw new AfsBaseException("同步案件数据失败！");
        }

//        AfsTransEntity<ChannelWitnessInfoTemp> transEntity =senderChannelToCaseImpl.sendWitnessToCase(aa);
//        senderChannelToCase.sendWitnessToCase(transEntity);


    }

    @ApiOperation(value = "通过id，见证人状态")
    @RequestMapping(value = "/upStatus", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public IResponse<Boolean> upStatus(@RequestBody ChannelWitnessInfoTemp channel) {

        if(channel.getId()==null){
            return  IResponse.fail("请选择见证人！");
        }

        if(channel.getStatus()==null||channel.getStatus()==""){
            return  IResponse.fail("请选择修改状态!");
        }

        // 先根据id 查这个信息
        ChannelWitnessInfoTemp chan = channelWitnessInfoTempService.getById(channel.getId());
        chan.setStatus(channel.getStatus());
        chan.setUpdateTime(new Date(System.currentTimeMillis()));
        chan.setUpdateBy(SecurityUtils.getUsername());
        channelWitnessInfoTempService.updateById(chan);
        return new IResponse<Boolean>().setMsg("修改数据成功");
    }

    @ApiOperation(value = "通过id，查询见证人的放款权限")
    @RequestMapping(value = "/checkRole", method = RequestMethod.POST)
    @ResponseBody
    public Object checkRole(@RequestBody JSONObject json) {
        Map<String,Object> map=new HashMap<>();
        try {
            String str = json.getString("ids");
            // 存放款权限的传递参数
            List<ChannelCardDTO> upIds =new ArrayList<>();

            List<String> cards=new ArrayList<>();
            //截取字符串
            String[] ids = str.split(",");
            for (int j = 0; j < Arrays.asList(ids).size(); j++) {
                Long id = Long.valueOf(Arrays.asList(ids).get(j));
                ChannelWitnessInfoTemp temp =channelWitnessInfoTempService.getById(id);

                ChannelCardDTO dto=new ChannelCardDTO();
                dto.setCard(temp.getWitnessIdCard());
                dto.setChannelId(temp.getChannelId());
                if(WitnessDic.BUSINESS_ATTRIBUTES_NEW.equals(temp.getBusinessAttributes())){
                    dto.setBusinessAttributes(CarTypeEnum.newCar);
                }else {
                    dto.setBusinessAttributes(CarTypeEnum.oldCar);
                }
                upIds.add(dto);

                cards.add(temp.getWitnessIdCard());
            }
            // 查询角色权限
            Map<String, String> requestHeader = new HashMap<>();
            requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
            requestHeader.put("clientSecret",channelConfig.getApplyAdminClientSecret());
            IResponse aa=channelOnlineSyncService.findWitnessRole(upIds,requestHeader);
            if("0000".equals(aa.getCode())){
                List<String> aas=new ArrayList<>();
                aas= (List<String>) aa.getData();
                List<ChannelWitnessInfoTemp> temps=new ArrayList<>();
                if(aas.size()>0){
                    temps=channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda()
                            .in(ChannelWitnessInfoTemp::getWitnessIdCard, aas));
                }
                map.put("adminUser",temps);
            }else {
                throw new AfsBaseException("查询权限账号失败！");
            }
            // 查询进件的正在见证的订单
            Map<String, String> header = new HashMap<>();
            header.put("clientId", channelConfig.getApplyClientId());
            header.put("clientSecret",channelConfig.getApplyClientSecret());
            IResponse bb =channelUseApplyService.queryWitnessIdCard(cards,header);
            if("0000".equals(bb.getCode())){
                List<String> bbs=new ArrayList<>();
                bbs= (List<String>) bb.getData();
                List<ChannelWitnessInfoTemp> temps=new ArrayList<>();
                if(bbs.size()>0){
                    temps=channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda()
                            .in(ChannelWitnessInfoTemp::getWitnessIdCard, bbs));
                }
                map.put("applyUser",temps);
            }else {
                throw new AfsBaseException("查询见证中的合同失败！");
            }
            map.put("code","0000");

        }catch (Exception e){
            logger.error(e.getMessage(), e);
            map.put("code","9999");
        }

        return map;
    }

    @RequestMapping(value = "/upAllByIds", method = RequestMethod.POST)
    @ApiOperation(value = "批量通过ids停用")
    @Transactional
    @ResponseBody
    public IResponse<Boolean> upAllByIds(@RequestBody JSONObject json) {
        String startStopReason = json.getString("startStopReason");
        String str = json.getString("ids");
        if(str.length()==0){
            return IResponse.fail("请选择见证人！");
        }
        List<ChannelCardDTO> upIds =new ArrayList<>();
        //截取字符串
        String[] ids = str.split(",");

        //同步案件使用
        List<Long> caseList =new ArrayList<>();
        //转换long类型的数组
        for (int j = 0; j < Arrays.asList(ids).size(); j++) {
            Long id = Long.valueOf(Arrays.asList(ids).get(j));
            caseList.add(id);
            ChannelWitnessInfoTemp chan = channelWitnessInfoTempService.getById(id);

            ChannelCardDTO dto=new ChannelCardDTO();
            dto.setCard(chan.getWitnessIdCard());
            dto.setChannelId(chan.getChannelId());
            if(WitnessDic.BUSINESS_ATTRIBUTES_NEW.equals(chan.getBusinessAttributes())){
                dto.setBusinessAttributes(CarTypeEnum.newCar);
            }else {
                dto.setBusinessAttributes(CarTypeEnum.oldCar);
            }
            upIds.add(dto);
            if(chan!=null){
                if(!WitnessDic.STATUS_STOP.equals(chan.getStatus())){
                    chan.setStatus(WitnessDic.STATUS_STOP);
                    chan.setUpdateTime(new Date(System.currentTimeMillis()));
                    chan.setUpdateBy(SecurityUtils.getUsername());
                    chan.setCeaseTime(new Date(System.currentTimeMillis()));
                    chan.setStartStopReason(startStopReason);
                    channelWitnessInfoTempService.updateById(chan);
                }
            }

        }
        // 批量停用案件见证人账号
        if(caseList.size()>0){
            Map<String,String> headers = new HashMap<String,String>();
            headers.put("clientId",channelConfig.getCaseClientId());
            headers.put("clientSecret",channelConfig.getCaseClientSecret());
            IResponse result=channelUseCaseService.upStatusWitnessByChannelIds(caseList,headers);
            if(CommonConstants.SUCCESS.equals(result.getCode())){

            }else {
                throw new AfsBaseException("批量停用失败！");
            }
        }
        // 去提供用见证人的系统账号
        if(upIds.size()>0){
            Map<String, String> requestHeader = new HashMap<>();
            requestHeader.put("clientId", channelConfig.getApplyAdminClientId());
            requestHeader.put("clientSecret",channelConfig.getApplyAdminClientSecret());
            IResponse result=channelOnlineSyncService.stopWitnessInfo(upIds,requestHeader);
            if(CommonConstants.SUCCESS.equals(result.getCode())){

            }else {
                throw new AfsBaseException("批量停用失败！");
            }

        }
        return new IResponse<Boolean>().setMsg("批量通过id更新数据成功");
    }

    @Transactional
    @PostMapping("/toExamine")
    @ApiOperation(value = "见证人审核")
    public  IResponse toExamine(@RequestBody ChannelWitnessInfoTemp carRelTemp) throws JsonProcessingException {

        carRelTemp.setUpdateBy(SecurityUtils.getUsername());
        carRelTemp.setUpdateTime(new Date(System.currentTimeMillis()));
        if(WitnessDic.STATUS_PASS.equals(carRelTemp.getStatus())){
            channelWitnessInfoTempService.update(Wrappers.<ChannelWitnessInfoTemp>lambdaUpdate().set(ChannelWitnessInfoTemp::getStartStopReason,null).eq(ChannelWitnessInfoTemp::getId, carRelTemp.getId()));
            carRelTemp.setApproveTime(new Date(System.currentTimeMillis()));
        }
        boolean result =channelWitnessInfoTempService.updateById(carRelTemp);
        ChannelWitnessInfoTemp aa =channelWitnessInfoTempService.getById(carRelTemp.getId());
        // 如果通过了要去修改案件那边信息
        if(WitnessDic.STATUS_PASS.equals(aa.getStatus())){
            comAttachementFileTempService.remove(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.witnessApply.toString()));
            //把影像资料存储
            List<ComAttachmentFile> fileList =comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.witnessApply.toString()));
            if(fileList.size()>0){
                for(ComAttachmentFile file:fileList){
                    ComAttachementFileTemp fileTemp=new ComAttachementFileTemp();
                    BeanUtils.copyProperties(file, fileTemp);
                    fileTemp.setId(null);
                    comAttachementFileTempService.save(fileTemp);
                }
            }
            this.sendCaseAdmin(aa);
        }
        WorkTaskDetail work =workTaskDetailService.list(Wrappers.<WorkTaskDetail>query().lambda().eq(WorkTaskDetail::getBusinessKey, carRelTemp.getId()).eq(WorkTaskDetail::getBizDataId,aa.getDataId().toString())).get(0);
        if (WitnessDic.STATUS_PASS.equals(carRelTemp.getStatus())) {
            // 如果是通过
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(carRelTemp.getId());
            dto.setApprove("1");
            dto.setBizDataId(work.getBizDataId());
            submit(dto);

        }else if(WitnessDic.STATUS_RETURN.equals(carRelTemp.getStatus())){
            // 这边进来是退回
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(carRelTemp.getId());
            dto.setApprove("2");
            dto.setBizDataId(work.getBizDataId());

            submit(dto);


        }else if(WitnessDic.STATUS_REFUSE.equals(carRelTemp.getStatus())){
            // 先删除自己的数据
            comAttachmentFileService.remove(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachmentFile::getBelongNo,ChannelNode.witnessApply.toString()));
            // 去修改进件的影像资料
            List<ComAttachementFileTemp> list=comAttachementFileTempService.list(Wrappers.<ComAttachementFileTemp>query().lambda().eq(ComAttachementFileTemp::getBusiNo,carRelTemp.getId().toString()).eq(ComAttachementFileTemp::getBelongNo,ChannelNode.witnessApply.toString()));
            for(ComAttachementFileTemp fileTemp:list){
                ComAttachmentFile file=new ComAttachmentFile();
                BeanUtils.copyProperties(fileTemp, file);
                file.setId(null);
                comAttachmentFileService.save(file);
            }
            if(list.size()>0){
                List<ComAttachmentFile> list2 = JSONUtil.parseArray(list).toList(ComAttachmentFile.class);
                ComAttachmentFileDataVo dataVo=new ComAttachmentFileDataVo();
                dataVo.setComAttachmentFileList(list2);
                AfsTransEntity<ComAttachmentFileDataVo> transEntity = new AfsTransEntity<>();
                transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_CHANNEL_FILE_APPLY);
                transEntity.setData(dataVo);
                senderChannelToApply.sendWitnessFile(transEntity);
            }

            // 这边进来是拒绝
            SubmitDTO dto =new SubmitDTO();
            dto.setRegisterId(carRelTemp.getId());
            dto.setApprove("3");
            dto.setBizDataId(work.getBizDataId());

           submit(dto);
            // 看看这条数据有没有备案成功过，如果有返还原来的数据
            Map<String,String> headers = new HashMap<String,String>();
            headers.put("clientId",channelConfig.getCaseClientId());
            headers.put("clientSecret",channelConfig.getCaseClientSecret());
            IResponse res=channelUseCaseService.getWitness(aa,headers);
            if(CommonConstants.SUCCESS.equals(res.getCode())){
                if(res.getData()!=null){
                    log.info("*****************回显数据："+res.getData());
                    String u = JSON.toJSONString(res.getData());
                    log.info("*****************回显数据："+u);
                    if(u!=null&&u!=""&&u!="null"){
                        ChannelWitnessInfoTemp temp=JSON.parseObject(JSON.parse(u).toString(),ChannelWitnessInfoTemp.class);
                        if(temp!=null){
                            //  还原原来的数据
                            channelWitnessInfoTempService.updateById(temp);
                        }
                    }
                }
            }else {
                throw new AfsBaseException("案件查询见证人信息失败");
            }
        }


        return result ? IResponse.success("成功"):IResponse.fail("失败");
    }



    @ApiOperation(value = "通过id删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public IResponse<Boolean> delete(@RequestBody ChannelWitnessInfoTemp witness ) {
        if(witness.getId()==null){
            return IResponse.fail("请选择见证人");
        }
        channelWitnessInfoTempService.removeById(witness.getId());
        return new IResponse<Boolean>().setMsg("通过id删除数据成功");
    }

    @ApiOperation(value = "通过身份证号查询见证人信息")
    @RequestMapping(value = "/getWitnessUser", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public IResponse getWitnessUser(@RequestBody ChannelWitnessInfoTemp  witness) {
        if(witness.getWitnessIdCard()==null||witness.getWitnessIdCard()==""){
            return IResponse.fail("请输入身份证号码！");
        }
        // 先根据id 查这个信息
        List<ChannelWitnessInfoTemp> list = channelWitnessInfoTempService.list(Wrappers.<ChannelWitnessInfoTemp>query().lambda().eq(ChannelWitnessInfoTemp::getWitnessIdCard,witness.getWitnessIdCard()));
        if(list.size()>0){
            return new IResponse<List<ChannelWitnessInfoTemp>>().setMsg("通过身份证号查询成功").setData(list);
        }else {
            return IResponse.fail("未查询到信息！");
        }
    }

    @PostMapping("/getWitnessById")
    @ApiOperation(value = "根据id 查询见证人信息")
    public IResponse<ChannelWitnessInfoTemp> getWitnessById(@RequestBody ChannelWitnessInfoTemp witness){
        ChannelWitnessInfoTemp list =channelWitnessInfoTempService.getById(witness.getId());
        // 判断是不是首次退回
        // 看看这条数据有没有备案成功过，如果有返还原来的数据
        Map<String,String> headers = new HashMap<String,String>();
        headers.put("clientId",channelConfig.getCaseClientId());
        headers.put("clientSecret",channelConfig.getCaseClientSecret());
        IResponse res=channelUseCaseService.getWitness(list,headers);
        if(CommonConstants.SUCCESS.equals(res.getCode())){
            if(res.getData()!=null){
                log.info("*****************回显数据："+res.getData());
                String u = JSON.toJSONString(res.getData());
                log.info("*****************回显数据："+u);
                if(u!=null&&u!=""&&u!="null"){
                    list.setFirstReturn("0");
                }
            }
        }else {
            throw new AfsBaseException("案件查询见证人信息失败");
        }
        return  IResponse.success(Boolean.TRUE).setMsg("查询成功").setData(list);
    }


}
